//
//  TableShowImagesCell+Config.swift
//  CooperSwift_Example
//
//  Created by 计海峰 on 2021/10/13.
//  Copyright © 2021 CocoaPods. All rights reserved.
//

import Foundation
import UIKit
import RxSwift
import RxGesture
import SKPhotoBrowser

public extension TableShowImagesCell {
    
    // MARK: - bind前 执行
    func layoutViews() {
        for _ in 0...2 { /// 默认添加两个
            createImgV()
        }
    }
    
    // MARK: - bind后 执行
    func loadData() {
        
        guard let cellModel = self.info as? TableShowImagesCellModel, let config = cellModel.model as? TableShowImagesConfig else {
            return
        }
        
        /// 补充缺少的 image view
        if showImageViews.count < config.imagesControls.count {
            for _ in 0...(config.imagesControls.count - showImageViews.count) {
                createImgV()
            }
        }
        
        /// 隐藏
        showImageViews.forEach { $0.isHidden = true }
        
        if !cellModel.isConfigDone { /// 执行一次配置
            cellModel.isConfigDone = true
            cellModel.once(showImageViews, cell: self)
        }
        cellModel.every(showImageViews, cell: self)
        
        if !cellModel.showByDefaultWay { return } /// 默认加载方式
        
        /// 延迟加载
        if (config.isDelay) {
            return
        }
        
        loadImagesActivity()
        
    }
    
    /// 分离出来 方便 delay 使用
    func loadImagesActivity() {
        guard let cellModel = self.info as? TableShowImagesCellModel, let config = cellModel.model as? TableShowImagesConfig else {
            return
        }
        for (idx, item) in config.imagesControls.enumerated() {
            guard let imageV = showImageViews[safe: idx] else {
                return
            }
            item.loadAll(imageV)
        }
    }
    
    /// 创建图片view
    func createImgV() {
        let imgV = UIImageView.init().then {
            $0.tag = showImageViews.count + 800
            /// 给个默认灰色图片
            $0.image = UIImage.init(color: UIColor(hex: "#f3f4f5"), size: CGSize(1, 1))
            $0.contentMode = .scaleAspectFill
            $0.isHidden = true
            $0.isUserInteractionEnabled = true
        }
        imgV.rx.tapGesture().when(.ended).subscribe(onNext: { [weak self] _ in
            //react to taps
            self?.showPhotos(imgV.tag - 800)
          }).disposed(by: stepBag)
        self.contentView.addSubview(imgV)
        self.showImageViews.append(imgV)
    }
    
    
    /// 图片浏览
    /// - Parameter idx:
    func showPhotos(_ idx: Int)  {
        guard let cellModel = self.info as? TableShowImagesCellModel, let config = cellModel.model as? TableShowImagesConfig else {
            return
        }
        var images = [String]()
        for item in config.imagesControls {
            guard let url = item.url else { return }
            images.append(url)
        }
        showPhotosBrowser(images, index: idx)
    }

}
